package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"goods_srv/goods"
	"goods_srv/internal/svc"
	"goods_srv/models"
	"goods_srv/pkg"
	"strconv"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建订单
func (l *OrderAddLogic) OrderAdd(in *goods.OrderAddRequest) (*goods.OrderAddResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	//查询用户是否存在
	var u models.User
	u.ID = uint(in.UserId)
	err = u.GetUserId()
	if err != nil {
		logx.Error("用户查询失败")
		return nil, errors.New("用户查询失败")
	}

	if u.ID == 0 {
		logx.Error("用户不存在")
	}

	//查询商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	err = g.GetGoods()
	if err != nil {
		logx.Error("商品查询失败")
		return nil, errors.New("商品查询失败")
	}

	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}

	//查看库存是否充足
	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	//生成订单
	var o models.Order
	orderSn := uuid.NewString()
	total := g.GoodsPrice * float64(in.Num)
	o = models.Order{
		UserId:     int(in.UserId),
		GoodsId:    int(in.GoodsId),
		OrderSn:    orderSn,
		OrderTotal: total,
	}
	err = o.Create()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}

	//扣减库存
	//cache.DelGoodsStock(int(in.GoodsId), int(in.Num))
	g.GoodsStock -= int(in.Num)
	err = g.UpdateStock()
	if err != nil {
		logx.Error("扣减商品库存失败")
		return nil, errors.New("扣减商品库存失败")
	}

	//生成订单商品
	var og models.OrderGoods
	og = models.OrderGoods{
		UserId:     int(in.UserId),
		GoodsId:    int(in.GoodsId),
		OrderSn:    orderSn,
		OrderTotal: total,
		GoodsTitle: g.GoodsTitle,
		GoodsPrice: g.GoodsPrice,
	}
	err = og.Create()
	if err != nil {
		logx.Error("订单商品表创建失败")
		return nil, errors.New("订单商品表创建失败")
	}

	//生成支付链接
	payURL := pkg.Alipay(orderSn, strconv.Itoa(int(total)))

	return &goods.OrderAddResponse{
		PayUrl: payURL,
	}, nil

}
